package gr.handmademarket.ui.panels;

import static gr.handmademarket.util.CommonStatics.PROFILE_PICS_PATH;
import static gr.handmademarket.util.CommonStatics.PROFILE_TEMP_PICS_PATH;
import gr.handmademarket.bl.operations.UpdateProfileOperation;
import gr.handmademarket.po.implementations.Seller;
import gr.handmademarket.po.interfaces.User;
import gr.handmademarket.ui.WebHandMadeMarketApplication;
import gr.handmademarket.ui.forms.ChangePasswordForm;
import gr.handmademarket.ui.pages.CategoryPage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.image.NonCachingImage;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.resource.ContextRelativeResource;

public class SellerProfilePanel 
extends Panel{

	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = 1L; 
	
	private TextField<String> userNameField = new TextField<String>("username");
	private TextField<String> firstNameField = new RequiredTextField<String>("firstName");
	private TextField<String> lastNameField = new RequiredTextField<String>("lastName");
	private TextArea<String> shortBioField = new TextArea<String>("shortBio");
	private TextArea<String> shopNotesField = new TextArea<String>("shopNotes");
	
	private Form<Seller> form;
	
	@SuppressWarnings("rawtypes")
	private Form<?> fileUploadForm = new Form("fform");
	private List<FileUpload> filesList = new ArrayList<FileUpload>();
	private IModel<List<FileUpload>> filesModel = new CompoundPropertyModel<List<FileUpload>>(filesList);
	private FileUploadField fileUploadField = new FileUploadField("fileUpload" , filesModel);
	private NonCachingImage profileImg;
	private NonCachingImage tempProfileImg;
	
	private Seller seller;
	private ChangePasswordForm passwordForm;
	
	private AjaxButton saveBtn = new AjaxButton("saveBtn") {
		
		/**
		 * serialVersionUID
		 */
		private static final long serialVersionUID = 1L;
		
		public void onSubmit(AjaxRequestTarget target, Form<?> form1) {
			if (tempProfileImg != null){
				String tempPath = PROFILE_TEMP_PICS_PATH + seller.getCode() + ".jpg";
				ServletContext context = WebHandMadeMarketApplication.get().getServletContext();
				String realTempPath = context.getRealPath(tempPath);
				String path = PROFILE_PICS_PATH + seller.getCode() + ".jpg";
				String realPath = context.getRealPath(path);
				File pic = new File(realPath);
				if (pic.exists()){
					pic.delete();
				}
				File tempPic = new File(realTempPath);
				tempPic.renameTo(pic);
			}
			UpdateProfileOperation updateOp = new UpdateProfileOperation();
			updateOp.setSeller(seller);
			updateOp.execute();
			seller = updateOp.getSeller();
			CategoryPage page = new CategoryPage(seller);
			setResponsePage(page);
		};
	};
	
	private AjaxButton previewBtn = new AjaxButton("previewBtn") {

		/**
		 * serialVersionUID
		 */
		private static final long serialVersionUID = 1L;
		
		@Override
		protected void onSubmit(AjaxRequestTarget target, Form<?> form1) {
			final FileUpload uploadedFile = fileUploadField.getFileUpload();
			if (uploadedFile != null) {
				String path = PROFILE_TEMP_PICS_PATH + seller.getCode() + ".jpg";
				ServletContext context = WebHandMadeMarketApplication.get().getServletContext();
				String realPath = context.getRealPath(path);
				File newFile = new File(realPath);
				if (newFile.exists()) {
					newFile.delete();
				}
				try {
					newFile.createNewFile();
					uploadedFile.writeTo(newFile);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				ContextRelativeResource resource = new ContextRelativeResource(path);
				tempProfileImg = new NonCachingImage("profileImg", resource); 
				SellerProfilePanel.this.get("fform:profileImg").replaceWith(tempProfileImg);
				target.add(SellerProfilePanel.this);
			}
		}
	};
	
	public SellerProfilePanel(String id, IModel<Seller> model) {
		super(id, model);
		setOutputMarkupId(true);
		seller = model.getObject();
		String path = PROFILE_PICS_PATH + model.getObject().getCode() + ".jpg";
		ContextRelativeResource resource = new ContextRelativeResource(path);
		profileImg = new NonCachingImage("profileImg", resource);
		userNameField.setEnabled(false);
		shopNotesField.setRequired(true);
		shortBioField.setRequired(true);
		form = new Form<Seller>("sform", model);
		form.add(userNameField,firstNameField, lastNameField, shopNotesField, shortBioField,saveBtn);
		add(form);
		fileUploadForm.add(fileUploadField,previewBtn,profileImg);
		fileUploadForm.setMultiPart(true);
		add(fileUploadForm);
		passwordForm = new ChangePasswordForm("passwordForm", new Model<User>(seller));
		add(passwordForm);
	}

}
